import os
import re



def scan_cmake_files(directory, target_string, context_lines=2):
    file_pattern = r'^CMakeLists\.txt$|\.cmake$'
    file_pattern = r'\.yaml$'
    target_pattern = re.compile(re.escape(target_string), re.IGNORECASE)

    # Walk through the directory and its subdirectories
    for root, _, files in os.walk(directory):
        for filename in files:
            file_path = os.path.join(root, filename)
            # Check if the filename matches the pattern
            if re.search(file_pattern, filename) or re.search(target_pattern, filename):
                with open(file_path, 'r', encoding='utf-8', errors='ignore') as file:
                    lines = file.readlines()
                    found = False

                    # Iterate through lines to find matches
                    for line_number, line in enumerate(lines):
                        if re.search(target_pattern, line):
                            if not found:
                                print("==================================================================================")
                                print(f"File: {file_path}")
                                found = True

                            start_line = max(0, line_number - context_lines)
                            end_line = min(len(lines), line_number + context_lines + 1)

                            # Print file name, line range, and matched line
                            print(f"Lines {start_line + 1}-{end_line}:")
                            for idx in range(start_line, end_line):
                                highlight_line = lines[idx].strip().replace(target_string, f"\033[1;31m{target_string}\033[0m", re.IGNORECASE)
                                print(f"{idx + 1}: {highlight_line}")

                    # Check if filename contains the target string
                    if re.search(target_pattern, filename) and not found:
                        print("==================================================================================")
                        print(f"File (name match): {file_path}")

if __name__ == '__main__':
    # 查找dir目录下的文件里有没有字符串str
    dir = r"D:\Iron\Work\spec-test\Test"
    str = r'target_link_libraries'
    scan_cmake_files(dir, str, context_lines=1)
